<template>
  <view class="patient-add">
    <view class="page-header">
      <view class="back-btn" @click="goBack">
        <u-icon name="arrow-left" color="#333" size="20"></u-icon>
      </view>
      <text class="header-title">添加患者</text>
      <view class="header-right"></view>
    </view>
    
    <view class="form-container">
      <u-form :model="formData" ref="uForm">
        <u-form-item label="手机号" required prop="phone">
          <u-input v-model="formData.phone" type="number" placeholder="请输入患者手机号" />
        </u-form-item>
        
        <view class="tip-box">
          <u-icon name="info-circle" color="#909399" size="16"></u-icon>
          <text class="tip-text">添加患者将发送绑定请求，需患者确认后生效</text>
        </view>
      </u-form>
      
      <view class="buttons">
        <button type="primary" @click="submitForm" class="uni-button">添加患者</button>
      </view>
    </view>
    
    <view class="result-section" v-if="searchResult">
      <view class="section-title">
        <text>搜索结果</text>
      </view>
      
      <view class="patient-card" v-if="searchResult.id">
        <view class="patient-avatar">
          <u-avatar :text="searchResult.name ? searchResult.name.charAt(0) : '?'" :size="50"></u-avatar>
        </view>
        <view class="patient-info">
          <view class="patient-name">{{ searchResult.name }}</view>
          <view class="patient-details">
            <text>{{ searchResult.sex === 'male' ? '男' : '女' }}</text>
            <text class="dot-divider">•</text>
            <text>{{ searchResult.age }}岁</text>
          </view>
          <view class="patient-phone">
            <u-icon name="phone" size="14"></u-icon>
            <text>{{ searchResult.phone }}</text>
          </view>
        </view>
      </view>
      
      <view class="no-result" v-else>
        <u-empty mode="search" text="未找到该患者"></u-empty>
      </view>
    </view>
    
    <uni-popup ref="confirmPopup" type="dialog">
      <uni-popup-dialog 
        title="确认添加" 
        content="确定向该患者发送绑定申请？" 
        :before-close="true" 
        @confirm="confirmBinding"
        @close="() => {}"
      ></uni-popup-dialog>
    </uni-popup>
    
    <view class="loading" v-if="loading">
      <uni-load-more status="loading" :content-text="{ contentdown: '加载中...' }"></uni-load-more>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { useBindingStore } from '@/store/modules/useBindingStore';
import { usePatientStore } from '@/store/modules/useDoctorStore';

const bindingStore = useBindingStore();
const patientStore = usePatientStore();
const uForm = ref(null);
const confirmPopup = ref(null);

const loading = ref(false);
const searchResult = ref(null);

const formData = reactive({
  phone: ''
});

// 表单提交
const submitForm = () => {
  if (!formData.phone || formData.phone.length !== 11) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none'
    });
    return;
  }
  
  searchPatient();
};

// 搜索患者
const searchPatient = async () => {
  loading.value = true;
  try {
    // 调用bindingStore的add函数
    const result = await bindingStore.add(formData.phone);
    
    if (result) {
      searchResult.value = result;
      // 使用 uni-popup 组件打开弹窗
      confirmPopup.value.open();
    } else {
      uni.showToast({
        title: '未找到该手机号关联的用户',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('搜索患者失败:', error);
    uni.showToast({
      title: error.message || '搜索失败，请重试',
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
};

// 确认绑定
const confirmBinding = async () => {
  loading.value = true;
  try {
    if (!searchResult.value) return;
    
    // 构建绑定数据
    const bindingData = {
      id: searchResult.value.id,
      name: searchResult.value.name,
      sex: searchResult.value.sex,
      age: searchResult.value.age,
      phone: searchResult.value.phone,
      bloodType: searchResult.value.bloodType,
    };
    
    // 添加绑定关系
    await bindingStore.addBinding(bindingData);
    
    // 刷新患者列表
    await patientStore.fetchPatientList();
    
    uni.showToast({
      title: '绑定申请已发送',
      icon: 'success'
    });
    
    // 延迟返回上一页
    setTimeout(() => {
      goBack();
    }, 1500);
  } catch (error) {
    console.error('添加患者失败:', error);
    uni.showToast({
      title: error.message || '添加失败，请重试',
      icon: 'none'
    });
  } finally {
    loading.value = false;
    // 关闭弹窗
    confirmPopup.value.close();
  }
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};
</script>

<style lang="scss" scoped>
.patient-add {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.page-header {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #ffffff;
  position: sticky;
  top: 0;
  z-index: 10;
  
  .back-btn {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .header-title {
    flex: 1;
    text-align: center;
    font-size: 34rpx;
    font-weight: bold;
  }
  
  .header-right {
    width: 60rpx;
  }
}

.form-container {
  margin: 30rpx;
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  
  .buttons {
    margin-top: 50rpx;
  }
  
  .uni-button {
    background-color: #2979ff;
    color: #ffffff;
    border-radius: 10rpx;
    font-size: 32rpx;
    height: 90rpx;
    line-height: 90rpx;
    width: 100%;
  }
  
  .tip-box {
    display: flex;
    align-items: center;
    background-color: #f8f9fa;
    padding: 20rpx;
    border-radius: 8rpx;
    margin-top: 20rpx;
    
    .tip-text {
      margin-left: 10rpx;
      font-size: 26rpx;
      color: #909399;
    }
  }
}

.result-section {
  margin: 30rpx;
  
  .section-title {
    font-size: 30rpx;
    font-weight: bold;
    margin-bottom: 20rpx;
    color: #333;
  }
  
  .patient-card {
    display: flex;
    align-items: center;
    background-color: #fff;
    padding: 30rpx;
    border-radius: 16rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    
    .patient-avatar {
      margin-right: 20rpx;
    }
    
    .patient-info {
      flex: 1;
      
      .patient-name {
        font-size: 32rpx;
        font-weight: bold;
        margin-bottom: 8rpx;
      }
      
      .patient-details {
        font-size: 26rpx;
        color: #666;
        margin-bottom: 6rpx;
        
        .dot-divider {
          margin: 0 10rpx;
        }
      }
      
      .patient-phone {
        display: flex;
        align-items: center;
        font-size: 26rpx;
        color: #666;
        
        text {
          margin-left: 8rpx;
        }
      }
    }
  }
  
  .no-result {
    padding: 40rpx 0;
  }
}

.loading {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.7);
  z-index: 999;
}
</style>